import random
import string

from common.tools import Tool
from common.conf import conf


class Invite:
    def __init__(self):
        self.c = conf()
        self.t = Tool()

    def register_ok(self, s):  # s 是register
        call_id = self.t.line_by_word(s, "Call-ID:")
        from_s = self.t.line_by_word(s, "From:")
        to_s = self.t.line_by_word(s, "To:")
        via = self.t.line_by_word(s, "Via:")
        cseq = self.t.line_by_word(s, "CSeq:")
        s = 'SIP/2.0 200 OK\n'
        s += f"Via: {via}\n"
        s += f"From: {to_s}\n"
        s += f"To: {from_s}\n"
        s += f"Call-ID: {call_id}\n"
        s += f"CSeq: {cseq}\n"
        return s

    # TODO 请求设备视频流 这msg是message call id 作为 y,会被zlmeidalkit 按照cid2ssrc的逻辑转化成视频url stream id  . call_id bye的是一样,
    #  所以存入redis,可以bye的时候继续invite

    def invite(self, cam_id, chan):
        q = self.c.col.find_one({"cam_id": cam_id})
        if q is None: return
        cid = self.t.from_camId_chanId_to_cid(cam_id, chan)
        ssrc = self.t.from_camId_chanId_to_ssrc(cam_id, chan)
        print(ssrc)
        # 向摄像机发送Invite消息,消息头域中携带 Subject字段,表明点播的视频源ID、发送方媒体流序列号、ZLMediaKit接收流使用的IP、端口号、 接收端媒体流序列号等参数,SDP消息体中 s字段为“Play”代表实时点播，y字段描述SSRC值,f字段描述媒体参数。

        # 注册前都要bye,把注册间隔的时间改长
        # 必须携带Subject头域，值为 摄像头通道ID:通道号,通道ID(主叫的sip id):通道号
        p = f"v=0\r\n"
        p += f"o={cam_id} 0 0 IN IP4 {self.c.zl_ip}\r\n"
        p += f"s=Play\r\n"
        # 流媒体ip
        p += f"c=IN IP4 {self.c.zl_ip}\r\n"
        p += f"t=0 0\r\n"
        # 10002是流媒体服务器的端口号，建议偶数端口    在平台播放视频每次播放1分钟左右，视频流就会出现停止的情况。针对该现象，我们立即进行排查  经过抓包发现，下级会主动发送bye信令，导致流主动断开。

        # p += f"m=video {zl['port']} TCP/RTP/AVP 96 98 97\r\n" #TCP
        p += f"m=video {self.c.zl_port} RTP/AVP 96 98 97\r\n" # UDP 96 h264
        p += f"a=rtpmap:96 PS/90000\r\n"
        p += f"a=recvonly\r\n"
        # sdp 中穿进去 y=cid,生成url ssrc
        p += f"y={cid}\r\n"

        tag = ''.join(random.choices(string.digits, k=10))
        branch = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
        s = f"INVITE sip:{cam_id}@{q['ip']}:{q['port']} SIP/2.0\n"
        s += f"Via: SIP/2.0/UDP {self.c.sip_ip}:{self.c.sip_port};rport;branch={branch}\n"
        s += f"From: <sip:{self.c.sip_id}@{self.c.sip_domain}>;tag={tag}\n"
        s += f"To: <sip:{cam_id}@{q['ip']}:{q['port']}>\n"
        s += f"Call-ID: {cid}\n"
        s += f"CSeq: 20 INVITE\n"
        s += f"Subject: {cam_id}:{chan},{self.c.sip_id}:1\n"
        s += f"Max-Forwards: 70\n"
        s += f"Contact: <sip:{self.c.sip_id}@{self.c.sip_ip}:{self.c.sip_port}>\n"
        s += f"Content-Type: application/sdp\n"
        s += f"Allow: INVITE,ACK,OPTIONS,BYE,CANCEL, UPDATE ,PRACK,REFER,SUBSCRIBE,NOTIFY,MESSAGE\n"
        s += f"Content-Length: {len(p)}\n\n"
        s += p
        return cid, s

    def ack(self, msg):  # 这个msg是invite回复
        call_id = self.t.line_by_word(msg, "Call-ID:")
        cam_id = msg[(msg.find('To:') + 9):msg.find('>', msg.find('To:'))]
        from_s = self.t.line_by_word(msg, "From:")
        to_s = self.t.line_by_word(msg, "To:")
        via = self.t.line_by_word(msg, "Via:")

        s = f"ACK sip:{cam_id} SIP/2.0\n"
        s += f"Call-ID: {call_id}\n"
        s += f"CSeq: 20 ACK\n"
        s += f"From: {from_s}\n"
        s += f"To: {to_s}\n"
        s += f"Max-Forwards: 70\n"
        s += f"Via: {via}\n"
        s += f"Content-Length: 0\n"
        return s

    def bye(self, msg):  # bye
        call_id = self.t.line_by_word(msg, "Call-ID:")
        cam_id = msg[(msg.find('from:') + 9):msg.find('>', msg.find('To:'))]
        from_s = self.t.line_by_word(msg, "From:")
        to_s = self.t.line_by_word(msg, "To:")
        via = self.t.line_by_word(msg, "Via:")
        bye = self.t.line_by_word(msg, "CSeq:")
        s = "SIP/2.0 200 OK\n"
        s += f"Via: {via}\n"
        s += f"From: {to_s}\n"
        s += f"To: {from_s}\n"
        s += f"Call-ID: {call_id}\n"
        s += f"CSeq: {bye}\n"
        s += f"Content-Length: 0\n"
        return s


if __name__ == '__main__':
    s = '''REGISTER sip:34020000002000000001@3402000000 SIP/2.0
Via: SIP/2.0/UDP 192.168.0.120:5060;rport;branch=z9hG4bK1226413297
From: <sip:34020000001320000001@3402000000>;tag=1891075390
To: <sip:34020000001320000001@3402000000>
Call-ID: 1294620708
CSeq: 1 REGISTER
Contact: <sip:34020000001320000001@192.168.0.120:5060>
Max-Forwards: 70
User-Agent: IP Camera
Expires: 3600
Content-Length: 0
    '''
    print(0x2e & 0x1f)
